package assfur.eran.utils;

import assfur.eran.config.ConfigManger;
import assfur.eran.config.MetaConfig;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import java.io.ByteArrayOutputStream;

public class SVNWrap {

    private String mUserName;
    private String mPwd;
    private String mURL;
    private SVNRepository mRepository;

    public SVNWrap() {
        MetaConfig metaConfig = ConfigManger.getInstance().getMeta();
        mUserName = metaConfig.svnUserName;
        mPwd = metaConfig.svnPwd;
        mURL = metaConfig.svnURL;
    }

    public void initialize() {

         /*
         * For using over http:// and https://
         */
        DAVRepositoryFactory.setup();
        /*
         * For using over svn:// and svn+xxx://
         */
        SVNRepositoryFactoryImpl.setup();

        /*
         * For using over file:///
         */
        FSRepositoryFactory.setup();

        try {
            /*
             * Creates an instance of SVNRepository to work with the repository.
             * All user's requests to the repository are relative to the
             * repository location used to create this SVNRepository.
             * SVNURL is a wrapper for URL strings that refer to repository locations.
             */
            mRepository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(mURL));
        } catch (SVNException e) {
            /*
             * Perhaps a malformed URL is the cause of this exception
             */
            System.err.println("error while creating an SVNRepository for the location '" + mURL + "': " + e.getMessage());
            System.exit(1);
        }

        /*
         * User's authentication information (name/password) is provided via  an
         * ISVNAuthenticationManager  instance.  SVNWCUtil  creates  a   default
         * authentication manager given user's name and password.
         *
         * Default authentication manager first attempts to use provided user name
         * and password and then falls back to the credentials stored in the
         * default Subversion credentials storage that is located in Subversion
         * configuration area. If you'd like to use provided user name and password
         * only you may use BasicAuthenticationManager class instead of default
         * authentication manager:
         *
         *  authManager = new BasicAuthenticationsManager(userName, userPassword);
         *
         * You may also skip this point - anonymous access will be used.
         */
        ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(mUserName, mPwd.toCharArray());
        mRepository.setAuthenticationManager(authManager);
    }


    public String getFileSVNVersion(String _svnPath) {
          /*
         * This Map will be used to get the file properties. Each Map key is a
         * property name and the value associated with the key is the property
         * value.
         */
        SVNProperties fileProperties = new SVNProperties();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            /*
             * Checks up if the specified path really corresponds to a file. If
             * doesn't the program exits. SVNNodeKind is that one who says what is
             * located at a path in a revision. -1 means the latest revision.
             */
            SVNNodeKind nodeKind = mRepository.checkPath(_svnPath, -1);

            if (nodeKind == SVNNodeKind.NONE) {
                System.err.println("There is no entry at '" + mURL + "'.");
                System.exit(1);
            } else if (nodeKind == SVNNodeKind.DIR) {
                System.err.println("The entry at '" + mURL + "' is a directory while a file was expected.");
                System.exit(1);
            }

            /*
             * Gets the contents and properties of the file located at filePath
             * in the repository at the latest revision (which is meant by a
             * negative revision number).
             */
            mRepository.getFile(_svnPath, -1, fileProperties, baos);

        } catch (SVNException e) {
            System.err.println("error while fetching the file contents and properties: " + e.getMessage());
            System.exit(1);
        }
        return fileProperties.getStringValue(SVNProperty.COMMITTED_REVISION);
    }

}
